import {getOwnAllProperty} from "../object/getOwnAllProperty";
import {toType} from "./toType";

/**
 * 浅克隆，仅克隆第一层
 * @param obj
 */
export function shallowClone(obj: unknown) {
    const type = toType(obj)
    // 如果是基本数据类型，直接返回这个值
    if (/^null|undefined|bigint|symbol|string|number|boolean$/.test(type)) return obj;
    // 如果是函数，返回一个新的代理函数，但是和原来的函数执行结果保持一致
    if (/^function$/.test(type)) {
        return function proxy(...args: any[]) {
            (obj as Function)(...args)
        }
    }
    // 如果是Date|RegExp|Error对象，新创建一个和他们一样的对象
    if (/^date|regexp$/.test(type)) return new (obj as any).constructor(obj)
    if (/^error$/.test(type)) return new Error((obj as any).message)
    // 否则如果是Object|Array, 循环遍历而且仅克隆第一层
    let keys = getOwnAllProperty(obj),
        clone = {}
    if (/^array$/.test(type)) clone = []
    keys.forEach(key => {
        (clone as any)[key] = (obj as any)[key]
    })
    return clone
}